package com.study.springbootshiro.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义的Realm
 * @author weixiaochun
 */
public class UserRealm extends AuthorizingRealm {

    Logger logger = LoggerFactory.getLogger(UserRealm.class);

    /**
     * 执行认证的逻辑
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info("------------------ 认证逻辑 ------------------");
        //假设数据库的用户名和密码
        String name = "admin";
        String password = "admin";

        //编写shiro判断逻辑，判断用户名和密码
        //1、判断用户名
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        if(!usernamePasswordToken.getUsername().equals(name)){
            //用户名不存在，shiro底层回抛出UnknownAccountException
            return null;
        }

        //判断密码
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("", password, "");

        return authenticationInfo;
    }

    /**
     * 执行授权逻辑
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("------------------ 授权逻辑 ------------------");
        return null;
    }

}
